class UserModulesController < ApplicationController

  def index
    @user_modules = UserModule.all
  end

  def show
    @user_module = UserModule.find_by_user_id(current_user.user_id)
  end

  def new
    @user_module = UserModule.new
  end

  def edit
    @user_module = UserModule.find(params[:id])
  end

  def create
    @user_module = UserModule.new(params[:user_module])

    redirect_to(:controller => "inputs", :action => "configure", :id => @user_module.input_id, :output => @user_module.output_id)
   
  end

  def update
    @user_module = UserModule.find(params[:id])

    respond_to do |format|
      if @user_module.update_attributes(params[:user_module])
        flash[:notice] = 'UserModule was successfully updated.'
        format.html { redirect_to(@user_module) }
        format.xml  { head :ok }
      else
        format.html { render :action => "edit" }
        format.xml  { render :xml => @user_module.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /user_modules/1
  # DELETE /user_modules/1.xml
  def destroy
    @user_module = UserModule.find(params[:id])
    @user_module.destroy

    redirect_to(dashboard_path)
  end

  def save_input_prefs
    @prefs = "<options>"
    @user_module = UserModule.find(params[:user_module_id]) if params[:user_module_id] && !params[:user_module_id].empty?
    if @user_module.nil?
      @user_module = UserModule.new(:user_id => current_user.user_id, :input_id => params[:input_id], :output_id => params[:output_id])
    end
    
    @attrs = params
    
    #MO,WE,FR;13:00
    @schedule = ""
    params[:day].each do |day|
      @schedule << day
      @schedule << "," unless (day == params[:day].last)
    end

    @schedule << ";" << params[:time]

    @user_module.next_notification = params[:first_notif] << ", #{params[:time]}"


    @attrs.delete(:input_id)
    @attrs.delete(:output_id)
    @attrs.delete(:action)
    @attrs.delete(:controller)
    @attrs.delete(:day)
    @attrs.delete(:time)
    @attrs.delete(:first_notif)
    @attrs.delete(:user_module_id)
    @attrs.each {
      |key, value|
      @prefs << "<option><name>#{key}</name><value>#{value}</value></option>"
    }
    @prefs << "</options>"
    @user_module.preferences = @prefs
    @user_module.reschedule = @schedule
    @user_module.save
    redirect_to(:controller => "outputs", :action => "configure", :id => @user_module.output_id)
  end

end

